import React from 'react';
import { connect } from 'dva';
import { Modal, Form, Input, message } from 'antd';
import _ from 'lodash';
import { formItemLayout } from '../common';

const FormItem = Form.Item;
const mainPorps = [
  'id', 'state', 'createtime',
];

const defaultFormItems = [
  {
    label: '名称',
    id: 'name',
    rules: [
      {
        required: true,
        message: '名称不能为空',
      },
    ],
    component: <Input placeholder="请输入名称" />,
  },
  {
    label: '包数量',
    id: 'packageSize',
    rules: [
      {
        required: true,
        message: '包数量不能为空',
      },
    ],
    component: <Input placeholder="请输入包数量" type="number" />,
  },
  {
    label: '包价格',
    id: 'price',
    rules: [
      {
        required: true,
        message: '包价格不能为空',
      },
    ],
    component: <Input placeholder="请输入包价格" type="number" />,
  },
  {
    label: '导航页',
    id: 'guide',
    component: <Input placeholder="请输入导航页" />,
  },
];


class PackModal extends React.Component {
  constructor(p) {
    super(p);
    this.handleOk = this.handleOk.bind(this);
    const { data } = this.props;
    const formItems = _.cloneDeep(defaultFormItems);

    Object.keys(data).forEach((key) => {
      // 过滤掉一些不能更改的数据
      if (mainPorps.indexOf(key) >= 0) {
        return;
      }
      const index = _.findIndex(formItems, (item) => {
        return item.id === key;
      });
      if (index >= 0) {
        formItems[index].initialValue = data[key];
      } else {
        formItems.push({
          label: key,
          id: key,
          component: <Input placeholder={`请输入${key}`} />,
          initialValue: data[key],
        });
      }
    });

    this.state = {
      formItems,
    };
  }

  handleOk() {
    const {
      validateFields,
      getFieldsValue,
    } = this.props.form;
    const { dispatch, onFinish, data } = this.props;

    validateFields((error) => {
      if (error) {
        return;
      }

      const values = getFieldsValue();
      dispatch({
        type: 'record/updatePack',
        payload: {
          value: _.merge(data, values),
          onEnd: (err) => {
            if (err) {
              if (typeof err === 'string') {
                message.error(err);
              } else {
                message.error(JSON.stringify(err));
              }
            } else {
              message.success('更新成功');
              onFinish();
            }
          },
        },
      });
    });
  }

  render() {
    const { visible, onFinish, loading } = this.props;
    const {
      getFieldDecorator,
    } = this.props.form;
    return (
      <Modal
        title="编辑任务包"
        okText="确定"
        visible={visible}
        onCancel={onFinish}
        onOk={this.handleOk}
        confirmLoading={_.get(loading, 'effects["record/updatePack"]')}
      >
        <Form layout="horizontal">
          {
              this.state.formItems.map((item) => {
                return (
                  <FormItem label={item.label} hasFeedback {...formItemLayout}>
                    {
                      getFieldDecorator(
                        item.id, {
                          rules: item.rules,
                          initialValue: item.initialValue,
                        },
                      )(item.component)
                    }
                  </FormItem>
                );
              })
            }
        </Form>
      </Modal>
    );
  }
}

PackModal.defaultProps = {
  visible: false,
  onFinish: () => null,
  data: {},
  loading: {},
};

export default connect(state => state)(Form.create()(PackModal));

